from flask import Blueprint, jsonify, request
from app.err_no import errno_no
from loguru import logger
import json
import traceback
from app.db import dbCheckDish
from app.db.mongoClient import MongoError

blueprint = Blueprint('dish_check', __name__, url_prefix='/api/dish')


@blueprint.route('/v1/check_dishes', methods=['POST'])
def check_dishes():
    '''
    菜品审核(按餐厅档口)
    '''
    try:
        j_data = json.loads(request.data)
        diningNo = j_data.get('diningNo')
        stallNo = j_data.get('stallNo')
        dishIds = j_data.get('dishIds')
        if diningNo is None or len(diningNo) <= 0 \
            or stallNo is None or len(stallNo) <= 0 \
            or dishIds is None or len(dishIds) <= 0 :
            return jsonify(errno_no.ErrServerParam.data(None))

        res = dbCheckDish.check_dishes(diningNo, stallNo, dishIds)
        if res is None:
            return jsonify(errno_no.ErrServerDocumentNotExist.data(None))
            
        # 判断dishIds数组里是否符合要求
        bPass = True
        for v in dishIds:
            dishId = v.get('dishId')
            dishState = v.get('dishState')
            checkFailDesc = v.get('checkFailDesc')
            # isinstance 判断某个数是不是整数
            if dishId is None or len(dishId) <= 0 \
                or dishState is None or len(dishState) <= 0 \
                or checkFailDesc is None:
                bPass = False
                break

        if bPass is False:
            return jsonify(errno_no.ErrServerParam.data(None))

        return jsonify(errno_no.OK.data(None))
    except MongoError as e:
        logger.error(f'操作mongo异常:{e.__dict__},traceback={traceback.format_exc()}')
        return jsonify(errno_no.ErrServerRuntime.data(None))
    except Exception as e:
        logger.error(f'业务异常:{e.__dict__},traceback={traceback.format_exc()}')
        return jsonify(errno_no.ErrServerRuntime.data(None))


@blueprint.route('/v1/check_dishes_dishIds', methods=['POST'])
def check_dishes_dishIds():
    '''
    菜品审核(按菜品Id)
    '''
    try:
        j_data = json.loads(request.data)
        dishState = j_data.get('dishState')
        checkFailDesc = j_data.get('checkFailDesc')
        dishIds = j_data.get('dishIds')
        if dishState is None or len(dishState) <= 0 \
            or checkFailDesc is None \
            or dishIds is None or len(dishIds) <= 0:
            return jsonify(errno_no.ErrServerParam.data(None))

        dbCheckDish.check_dishes_dishIds(dishState, checkFailDesc, dishIds)

        return jsonify(errno_no.OK.data(None))
    except MongoError as e:
        logger.error(f'操作mongo异常:{e.__dict__},traceback={traceback.format_exc()}')
        return jsonify(errno_no.ErrServerRuntime.data(None))
    except Exception as e:
        logger.error(f'业务异常:{e.__dict__},traceback={traceback.format_exc()}')
        return jsonify(errno_no.ErrServerRuntime.data(None))